<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="loginName">
        <el-input
          v-model="queryParams.loginName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="员工ID" prop="employeeId">
        <el-input
          v-model="queryParams.employeeId"
          placeholder="请输入员工ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
          <treeselect style="display:inline-block;width:215px;" v-model="queryParams.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择部门" />
      </el-form-item>

      <el-form-item label="联系方式" prop="contactWay">
        <el-input
          v-model="queryParams.contactWay"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册日期" prop="registerDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
       <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="authAdd"
          :disabled="multiple"
        >权限分配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:employee:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column
        type="index"
        label="序号"
        width="60"
        :index="indexMethod"
        align="center"
      />
      <el-table-column label="用户名" align="center" prop="loginName" />
      <el-table-column label="ID" align="center" prop="employeeId" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="手机号" align="center" prop="contactWay" />
      <el-table-column label="邮箱" align="center" prop="email" width="180" />
      <el-table-column label="注册日期" align="center" prop="registerDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="最后登录时间" align="center" prop="lastLoginDate" width="180"/>
      <el-table-column label="最后登录IP" align="center" prop="lastLoginIp" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">注销</span>
          <span v-if="scope.row.status == 1">正常</span>
          <!-- <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/> -->
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="form.employeeId" placeholder="请输入员工ID" />
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="loginName">
          <el-input :disabled="form.id != null" v-model="form.loginName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="form.id == null" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactWay">
          <el-input v-model="form.contactWay" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="注册日期" prop="registerDate">
          <el-date-picker clearable
            style="width:100%;"
            v-model="form.registerDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择注册日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 权限分配 -->
    <el-dialog title="权限分配" :visible.sync="open1" width="1000px" append-to-body>
      <el-form ref="form" :model="form1" :rules="rules1" label-width="80px">
        <el-form-item label="员工信息" prop="name">
          <el-card class="box-card">
            <div class="text item">
              <span style="width:200px;display:inline-block;">员工ID</span>
              <span style="width:200px;display:inline-block;">员工姓名 </span>
            </div>
            <div v-for="item in employeeAuthList" :key="item.id" class="text item">
              <span style="width:200px;display:inline-block;">{{item.employeeId}}</span>
              <span style="width:200px;display:inline-block;">{{item.name}}</span>
            </div>
          </el-card>
        </el-form-item>
        
        <el-form-item label="系统权限" prop="sysId">
          <el-select
              v-model="form1.sysId"
              placeholder="系统权限"
              @change="getMenuList()"
            >
              <el-option
                v-for="item in sysList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
        </el-form-item>

        <el-form-item label="菜单" prop="menuId">
          <el-select
              v-model="form1.menuId"
              placeholder="菜单"
              @change="menuChange()"
            >
              <el-option
                v-for="item in menuList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
        </el-form-item>

        <el-form-item label="已选菜单" prop="name">
          <el-card class="box-card">
            <div v-for="item in selectMenuList" :key="item.id" class="text item">
              <span style="width:200px;display:inline-block;">{{item.name}}</span>
              <span @click="remove(item.id)" style="width:200px;display:inline-block;cursor:pointer;">删除</span>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee,addEmployeeMenu,queryMenu } from "@/api/system/employee";
import { listDept } from '@/api/system/authDept'
import { getAllAuth } from '@/api/system/authSys'
import { getListBySysId } from '@/api/system/authMenu'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Employee",
  dicts: ['employee_status'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工表格数据
      employeeList: [],

      deptOptions: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      dateRange: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        loginName: null,
        password: null,
        employeeId: null,
        name: null,
        deptId: null,
        deptName: null,
        contactWay: null,
        email: null,
        registerDate: null,
        isDel: null,
        version: null,
        createUserId: null,
        createUserName: null,
        updateUserId: null,
        updateUserName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      open1: false,
      employeeAuthList: [],
      sysList: [],
      menuList: [],
      selectMenuList: [],
        // 表单参数
      form1: {},
      // 表单校验
      rules1: {
      },
    };
  },
  created() {
    this.listDept()
    this.getList();
  },
  methods: {
    async getAllAuth() {
      let res = await getAllAuth()
      if(res.code == 200) {
        this.sysList = res.data
        console.log('this.sysList>' + JSON.stringify(this.sysList))
        if(this.sysList &&this.sysList.length >0) {
          this.form1.sysId = this.sysList[0].id
          this.getMenuList()
        }
      }
      this.$forceUpdate()
    },
    // 系统权限改变事件
    async getMenuList() {
      let res = await getListBySysId({sysId:this.form1.sysId})
      if(res.code == 200) {
        let array = [{
          id: 0,
          name: '请选择'
        }]
        if(res.data && res.data.length > 0) {
          this.menuList = array.concat(res.data)
        }else {
          this.menuList = array
        }
        this.form1.menuId = this.menuList[0].id
      }
      this.$forceUpdate()
    },
    // 菜单改变事件
    menuChange() {
      this.$forceUpdate()
      if(this.form1.menuId != 0) {
        let b = false
        this.selectMenuList.map(item => {
          if(item.id == this.form1.menuId) {
            b = true
          }
        })

        if(!b) {
          this.menuList.map(item => {
            if(item.id == this.form1.menuId) {
              this.selectMenuList.push(item)
            }
          })
        }
      }
    },
    // 删除选中的菜单
    remove(id) {
      this.selectMenuList = this.selectMenuList.filter(item => {
        if(item.id == id) {
          return false
        }
        return true
      })
    },
    indexMethod(index) {
      index = index + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      return index
    },
    /** 查询员工列表 */
    getList() {
      if (this.dateRange) {
        this.queryParams.startDate = this.dateRange[0] + " 00:00:00";
        this.queryParams.endDate = this.dateRange[1] + " 00:00:00";
      } else {
        this.queryParams.startDate = "";
        this.queryParams.endDate = "";
      }
      this.loading = true;
      listEmployee(this.queryParams).then(response => {
        this.employeeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    async listDept() {
      let res = await listDept()
      if(res.code == 200) {
        this.deptOptions = this.handleTree(res.data, "id");
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        loginName: null,
        password: null,
        employeeId: null,
        name: null,
        deptId: null,
        deptName: null,
        contactWay: null,
        email: null,
        registerDate: null,
        isDel: null,
        version: null,
        createUserId: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserName: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = ''
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmployee(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改员工";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if(this.form && this.form.registerDate && this.form.registerDate.lastIndexOf("00:00:00") < 0) {
              this.form.registerDate = this.form.registerDate + ' 00:00:00'
            }
            updateEmployee(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if(this.form && this.form.registerDate && this.form.registerDate.lastIndexOf("00:00:00") < 0) {
              this.form.registerDate = this.form.registerDate + ' 00:00:00'
            }
            addEmployee(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除员工编号为"' + ids + '"的数据项？').then(function() {
        return delEmployee(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/employee/export', {
        ...this.queryParams
      }, `employee_${new Date().getTime()}.xlsx`)
    },

    // 权限分配
    async authAdd() {
      console.log('authAdd')

      let array = []
      this.employeeList.map(item => {
        if(this.ids.includes(item.id)) {
          array.push(item)
        }
      })
      this.employeeAuthList = array
      console.log('this.employeeAuthList>' + JSON.stringify(this.employeeAuthList))

      // 菜单
      let res = await queryMenu({employeeIdList :this.ids})
      if(res.code == 200) {
        this.selectMenuList = res.data
      }
      
      console.log(this.ids)
      this.form1 = {}
      this.open1 = true

      await this.getAllAuth()
    },
    submitForm1() {
      console.log('submitForm1')

      let employeeIdList = []
      let menuIdList = []
      this.employeeAuthList.map(item => {
        employeeIdList.push(item.id)
      })
      this.selectMenuList.map(item => {
        menuIdList.push(item.id)
      })

      if(employeeIdList.length == 0) {
        this.$modal.msgError('员工不能为空')
        return 
      }
      if(menuIdList.length == 0) {
        this.$modal.msgError('菜单不能为空')
        return 
      }

      let param = {
        employeeIdList: employeeIdList,
        menuIdList: menuIdList
      }
      addEmployeeMenu(param).then(res => {
        if(res.code == 200) {
           this.$modal.msgSuccess("权限分配成功")
           this.open1 = false
        }else {
          this.$modal.msgError(res.msg)
        }
      })
    },
    cancel1() {
      this.open1 = false
    }


  }
};
</script>


<style scoped>
  .text {
    /* font-size: 14px; */
  }

  .item {
    /* margin-bottom: 10px; */
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    /* width: 300px; */
    /* height: 200px; */
  }
</style>
